package de.ifi.lmu.snitzelhunt.view;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.Toast;
import de.ifi.lmu.snitzelhunt.R;
import de.ifi.lmu.snitzelhunt.creator.Globals;
import de.ifi.lmu.snitzelhunt.participants.ParticipantsActivity;
import de.ifi.lmu.snitzelhunt.util.RouteServerUtility;
import de.ifi.lmu.snitzelhunt.util.responses.AsyncServer_RouteInfo_ReadforCreatorResponse;
import de.ifi.lmu.snitzelhunt.util.responses.Server_RouteInfo_ReadforCreatorResponse;


/**
 * @author Sarah Torma
 * 
 *         Main Class starts the activity and the user gets to choose whether to
 *         create an new route or to load a assigned route
 * 
 */
public class MainActivity extends ActionBarActivity implements
		OnMenuItemClickListener, AsyncServer_RouteInfo_ReadforCreatorResponse {

	
	public boolean debug =true;
	
	public static final String PREFS_PARTICIPANTS = Globals.PREFS_PARTICIPANTS;
	public static final String OLD_ROUTE_FLAG = "oldRouteFlag";
	public static final String NEW_ROUTE_FLAG = "newRouteFlag";

	private SharedPreferences settings;
	private String mPhoneNumber;

	// previous = 0 -> generiere neue Route
	// previous = 1 -> lade eigene Routen vom Server
	// previous = 2 -> mach letzte route fertig
	protected int previous;
	private boolean hasRoutesOnServer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		settings = getSharedPreferences(Globals.PREF_NAME, 0);
		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}
		Log.i("snitzelhunt util", "Online " + isOnline());
		Log.i("snitzelhunt util", "GPS " + isGPS());

	}

	private void checkForRoutes() {
		TelephonyManager tMgr = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
		mPhoneNumber = tMgr.getLine1Number();

		Log.i("main", "check for routes");

		if (mPhoneNumber != null) {
			if (mPhoneNumber.startsWith("01")) {
				mPhoneNumber = "+49"+ mPhoneNumber.substring(2);
			}
			new RouteServerUtility().readRouteInfo_forCreator(mPhoneNumber, this);
			Log.i("main", "checking routes for "+mPhoneNumber);
		} else {
			Log.i("main","no phone number found, skip search for routes");

		}
		
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/**
	 * When settings is clicked a how to explanation screen is shown
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		int id = item.getItemId();
		if (id == R.id.action_settings) {

			Intent howto = new Intent(this, Activity_HowTo.class);
			startActivity(howto);
		}

		return true;
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main, container,
					false);
			return rootView;
		}
	}

	/**
	 * When activity is resumed, set Buttons to non-clicked state
	 */
	@Override
	protected void onResume() {

		super.onResume();
		ImageButton starten = (ImageButton) findViewById(R.id.ButtonAbrufen);
		starten.setBackgroundResource(R.drawable.starten);

		ImageButton erstellen = (ImageButton) findViewById(R.id.ButtonErstellen);
		erstellen.setBackgroundResource(R.drawable.erstellen);

		checkForRoutes();
				
		starten.setEnabled(true);
	}

	/**
	 * @param myview
	 * 
	 *            Starting a new Activity when user wants to load an assigned
	 *            route/hunt
	 */
	public void loadHunt(final View myview) 
	{
		
		final SharedPreferences preferences = getSharedPreferences(PREFS_PARTICIPANTS, 0);

		final ImageButton button = (ImageButton) findViewById(R.id.ButtonAbrufen);
		button.setBackgroundResource(R.drawable.starten_dark);
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() 
		{
			public void run() 
			{

				// check if internet and gps is available
				if (!MainActivity.this.isOnline()) {
					callsettings("net");
				} else if (MainActivity.this.isGPS() == false) {
					callsettings("gps");
				}

				else 
				{
					PopupMenu createParticipants = new PopupMenu(MainActivity.this, myview);
					
					if(preferences.getBoolean(OLD_ROUTE_FLAG, false))
					{
						System.out.println("New Route: " + preferences.getBoolean(NEW_ROUTE_FLAG, true));
						
						createParticipants.getMenu().add("Neue Route starten");
						createParticipants.getMenu().add("Alte Route fortsetzen");
						createParticipants.show();
						
						createParticipants.setOnMenuItemClickListener(new OnMenuItemClickListener() 
						{
							
							@Override
							public boolean onMenuItemClick(MenuItem arg0) 
							{
								if (preferences.getBoolean(OLD_ROUTE_FLAG, false)) 
								{
									if(arg0.getTitle() == "Neue Route starten")
									{
										if(preferences.getBoolean(OLD_ROUTE_FLAG, true))
										{
											SharedPreferences.Editor editor = preferences.edit();
											editor.putBoolean("oldRouteFlag", false);
											editor.putBoolean("newRouteFlag", true);
											// Commit the edits!
											editor.commit();
											System.out.println("Menu: oldRouteFlag set to false");
											System.out.println("Menu: newRouteFlag set to true");
											
										}
									}
									if(arg0.getTitle() == "Alte Route fortsetzen")	
									{
										SharedPreferences.Editor editor = preferences.edit();
										editor.putBoolean("oldRouteFlag", true);
										editor.putBoolean("newRouteFlag", false);
										// Commit the edits!
										editor.commit();
										System.out.println("Menu: oldRouteFlag set to true");
										System.out.println("Menu: newRouteFlag set to false");
										
									
									}
									button.setBackgroundResource(R.drawable.starten);
									Intent loadHunt = new Intent(MainActivity.this,
											ParticipantsActivity.class);
									loadHunt.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
									startActivity(loadHunt);
								}
								return false;
							}
						});	
						
					}
					else
					{
						SharedPreferences.Editor editor = preferences.edit();
						editor.putBoolean("oldRouteFlag", false);
						// Commit the edits!
						editor.commit();
						
						button.setBackgroundResource(R.drawable.starten);
						Intent loadHunt = new Intent(MainActivity.this,
								ParticipantsActivity.class);
						loadHunt.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(loadHunt);						
					}	
					
					
					button.setEnabled(false);
				}
			}
		}, 100);

	}

	public void create(View v) {

		final ImageButton button = (ImageButton) findViewById(R.id.ButtonErstellen);
		button.setBackgroundResource(R.drawable.erstellen_dark);

		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			public void run() {

				button.setBackgroundResource(R.drawable.erstellen);

			}
		}, 100);

		PopupMenu createWhat = new PopupMenu(this, v);
		// createWhat.getMenuInflater().inflate(R.menu.create_menu,
		// createWhat.getMenu());
		createWhat.setOnMenuItemClickListener(this);

		// f�ge MenuItem "neue Route erstellen" hinzu
		createWhat.getMenu().add(R.string.createNew);
		// �berpr�fen, ob user bereits routen hochgeladen hat -> MenuItem
		// "vorhandene Route editieren"		
		if (hasRoutesOnServer) {
			createWhat.getMenu().add(R.string.editExisting);
		}
		// �berpr�fen, ob sich noch eine unvollst�ndige Route in den Preferences
		// befindet -> MenuItem "letzte Route fertigstellen"
		if (!settings.getBoolean(Globals.SENT_FLAG, true)) {
			createWhat.getMenu().add(R.string.continueEditingRoute);
		}

		createWhat.show();
	}
	
	

	@Override
	public boolean onMenuItemClick(MenuItem arg0) {

		// depending on the selected menu item, set the previous flag and call
		// createhunt
		if (arg0.getTitle() == getResources().getString(R.string.createNew)) {
			previous = 0;
			callCreateActivity();
		} else if (arg0.getTitle() == (getResources()
				.getString(R.string.editExisting))) {
			previous = 1;
			Intent showPrevRoutes = new Intent(this, Activity_MyRoutes.class);
			showPrevRoutes.putExtra("myNumber", mPhoneNumber);
			startActivity(showPrevRoutes);
			
		} else if (arg0.getTitle() == (getResources()
				.getString(R.string.continueEditingRoute))) {
			previous = 2;
			callCreateActivity();
		} else {
			Toast.makeText(this, "Menu machte seise" + arg0, Toast.LENGTH_SHORT)
					.show();
		}
		return false;
	}

	private void callsettings(final String thingsToEnable) {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.gps_disabled_message)
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {

								if (thingsToEnable.equals("net")) {
									Intent intent = new Intent(
											Settings.ACTION_SETTINGS);
									startActivity(intent);
								} else {
									startActivity(new Intent(
											android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
								}

							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		builder.setTitle("Internet und GPS aktivieren");
		builder.setIcon(R.drawable.intergps);

		AlertDialog alert = builder.create();
		alert.show();

	}

	private void callCreateActivity() {
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			public void run() {

				// check if internet and gps is available
				if (!MainActivity.this.isOnline()) {
					callsettings("net");
				} else if (!MainActivity.this.isGPS()) {
					System.out.println("GPS false");
					callsettings("gps");
				} else {
					Intent createHunt = new Intent(MainActivity.this,
							Activity_CreateHunt.class);
					/*
					 * If the activity being started is already running in the
					 * current task, then instead of launching a new instance of
					 * that activity, all of the other activities on top of it
					 * are destroyed and this intent is delivered to the resumed
					 * instance of the activity (now on top), through
					 * onNewIntent()
					 */

					createHunt.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					createHunt.putExtra("loadPrevious", previous);

					Log.i("main", "created intent with extra" + previous);
					startActivity(createHunt);
					Log.i("main", "neue Activity");
				}

			}
		}, 100);
	}

	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnected()) {
			return true;
		}
		return false;
	}

	public boolean isGPS() {
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
	}

	@Override
	public void processServer_RouteInfo_ReadforCreator(
			Server_RouteInfo_ReadforCreatorResponse response) {
		// TODO Auto-generated method stub
		
		if ( response.getHttpStatus() == 200) {
			if (response.getRinfo().getInfo().size() > 0) {
				hasRoutesOnServer = true;
				Log.i("main", "routen gefunden:"+response.getRinfo().getInfo().size());
			}
		} else {
			Log.e("main", "fehler beim abfragen der Routen. Fehler Nr. " + response.getHttpStatus());
		}
		
	}

}
